// 数据记录页面
const auth = require('../../utils/auth.js');
// 统一：弃用 config.baseUrl，改用 app.globalData.apiBaseUrl
// const config = require('../../utils/config');
const moment = require('../../utils/moment');

Page({
  data: {
    userInfo: {},
    loading: true,
    records: [],
    currentPage: 1,
    hasMore: true,
    loadingMore: false,
    
    // 筛选条件
  filterType: 'all', // all, vision, intervention, social, doctor
  // 默认放宽到 all，避免旧历史视力数据（>30天）初始被过滤导致“暂无数据”误判
  dateRange: 'all', // 7d, 30d, 90d, all
    
    // 统计信息
    statistics: {
      totalRecords: 0,
      visionRecords: 0,
      interventionRecords: 0,
  socialRecords: 0,
  doctorRecords: 0
    }
  },

  onLoad: function() {
    this.loadUserInfo();
    this.loadStatistics();
    this.loadRecords();
  },

  onPullDownRefresh: function() {
    this.setData({
      currentPage: 1,
      records: [],
      hasMore: true
    });
    this.loadStatistics();
    this.loadRecords();
  },

  onReachBottom: function() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadMoreRecords();
    }
  },

  // 加载用户信息
  loadUserInfo: function() {
  const userInfo = auth.getCurrentUser && auth.getCurrentUser();
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        loading: false
      });
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载统计信息
  loadStatistics: function() {
  wx.request({
      url: `${getApp().globalData.apiBaseUrl}/records/statistics`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${auth.getToken()}`
      },
      data: {
        dateRange: this.data.dateRange
      },
      success: (res) => {
    if (res.statusCode === 200 && (res.data.code === 0 || res.data.success)) {
          this.setData({
            statistics: res.data.data
          });
        }
      },
      fail: (error) => {
        console.error('加载统计信息失败:', error);
      }
    });
  },

  // 加载记录列表
  loadRecords: function() {
    this.setData({ loading: true });

  wx.request({
      url: `${getApp().globalData.apiBaseUrl}/records`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${auth.getToken()}`
      },
      data: {
        page: this.data.currentPage,
        limit: 20,
        type: this.data.filterType,
        dateRange: this.data.dateRange
      },
      success: (res) => {
        wx.stopPullDownRefresh();
        this.setData({ loading: false });
        
    if (res.statusCode === 200 && (res.data.code === 0 || res.data.success)) {
          const newRecords = res.data.data.records || [];
          this.setData({
            records: this.data.currentPage === 1 ? newRecords : [...this.data.records, ...newRecords],
            hasMore: newRecords.length === 20,
            currentPage: this.data.currentPage
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.stopPullDownRefresh();
        this.setData({ loading: false });
        console.error('加载记录失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 加载更多记录
  loadMoreRecords: function() {
    this.setData({ 
      loadingMore: true,
      currentPage: this.data.currentPage + 1
    });

  wx.request({
      url: `${getApp().globalData.apiBaseUrl}/records`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${auth.getToken()}`
      },
      data: {
        page: this.data.currentPage,
        limit: 20,
        type: this.data.filterType,
        dateRange: this.data.dateRange
      },
      success: (res) => {
        this.setData({ loadingMore: false });
        
    if (res.statusCode === 200 && (res.data.code === 0 || res.data.success)) {
          const newRecords = res.data.data.records || [];
          this.setData({
            records: [...this.data.records, ...newRecords],
            hasMore: newRecords.length === 20
          });
        }
      },
      fail: (error) => {
        this.setData({ loadingMore: false });
        console.error('加载更多记录失败:', error);
      }
    });
  },

  // 切换筛选类型
  onFilterTypeChange: function(e) {
    const filterType = e.currentTarget.dataset.type;
    if (filterType === this.data.filterType) return;
    // setData 异步，使用回调确保 currentPage 已重置再发起请求，避免读取旧页码导致空列表
    this.setData({
      filterType,
      currentPage: 1,
      records: [],
      hasMore: true
    }, () => {
      this.loadStatistics();
      this.loadRecords();
    });
  },

  // 切换日期范围
  onDateRangeChange: function(e) {
    const idx = parseInt(e.detail.value, 10);
    const map = ['7d','30d','90d','all'];
    const dateRange = map[idx] || 'all';
    this.setData({
      dateRange,
      currentPage: 1,
      records: [],
      hasMore: true
    }, () => {
      this.loadStatistics();
      this.loadRecords();
    });
  },

  // 查看记录详情
  viewRecordDetail: function(e) {
    const { id, type } = e.currentTarget.dataset;
    if(!id || !type){ return; }
    if (type === 'vision') {
      // 视力详情页面尚未在 app.json 列出？若未注册需补注册；保持现有路径
      wx.navigateTo({ url: `/pages/vision/detail/detail?id=${id}` });
    } else if (type === 'intervention') {
      // app.json 中存在旧路径 pages/intervention-detail/intervention-detail
      if (this.pageExists('/pages/intervention/detail/detail')) {
        wx.navigateTo({ url: `/pages/intervention/detail/detail?id=${id}` });
      } else {
        wx.navigateTo({ url: `/pages/intervention-detail/intervention-detail?id=${id}` });
      }
    } else if (type === 'social') {
      wx.navigateTo({ url: `/pages/social/detail/detail?id=${id}` });
    } else if (type === 'doctor') {
      wx.navigateTo({ url: `/pages/communication/detail/detail?id=${id}` });
    }
  },

  // 简单判断页面是否已注册（若不存在会在 navigateTo 时报错）
  pageExists(path){
    try {
      const pages = getApp().globalData?.__allPagesCache || getCurrentPages().map(p=>p.route);
      return pages.includes(path.replace(/^\//,''));
    } catch(e){ return true; }
  },

  // 导出数据
  exportData: function() {
    wx.showToast({
      title: '数据导出功能开发中',
      icon: 'none'
    });
  },

  // 格式化日期
  formatDate: function(dateString) {
    return moment(dateString).format('MM-DD HH:mm');
  },

  // 获取记录类型文本
  getRecordTypeText: function(type) {
    const typeMap = {
      'vision': '视力检测',
      'intervention': '干预记录',
      'social': '社交动态',
      'doctor': '医生交流'
    };
    return typeMap[type] || '未知类型';
  },

  // 获取记录图标
  getRecordIcon: function(type) {
    const iconMap = {
      'vision': '👁️',
      'intervention': '🏥',
      'social': '💬',
      'doctor': '🩺'
    };
    return iconMap[type] || '📝';
  }
});
